import 'package:get/get.dart';

import '../entity/play_list_enity.dart';
import '../utils/local_storage_utils.dart';

class PlayListController extends GetxController {
  final RxList<PlayListEntity> playlists = <PlayListEntity>[].obs;

  // 默认播放列表，id: -1, name: "默认"
  final PlayListEntity defaultPlaylist = PlayListEntity(id: -1, name: '默认', videoIds: []);

  @override
  void onInit() {
    super.onInit();
    loadPlaylists();
  }

  // 从本地存储加载播放列表
  Future<void> loadPlaylists() async {
    final savedPlaylists = await LocalStorageUtils.getStringList('playlists');

    if (savedPlaylists != null && savedPlaylists.isNotEmpty) {
      playlists.value = savedPlaylists.map((playlistJson) => PlayListEntity.fromJsonString(playlistJson)).toList();

      // 检查是否包含默认播放列表，如果没有则添加
      if (playlists.firstWhereOrNull((playlist) => playlist.id == -1) == null) {
        playlists.insert(0, defaultPlaylist);
      }
    } else {
      // 如果没有任何播放列表，则添加默认播放列表
      playlists.add(defaultPlaylist);
    }
  }

  // 保存播放列表到本地存储
  Future<void> savePlaylists() async {
    final playlistJsons = playlists.map((playlist) => playlist.toJsonString()).toList();
    await LocalStorageUtils.saveStringList('playlists', playlistJsons);
    playlists.refresh(); // 手动触发RxList的更新
  }

  // 添加播放列表（去重名称，ID为最大值+1）
  Future<bool> addPlaylist(String name) async {
    // 检查是否存在同名的播放列表
    if (playlists.any((playlist) => playlist.name == name)) {
      return false; // 名称已存在，返回失败
    }
    // 生成新的播放列表ID，取当前列表中最大的id值 + 1
    int newId;
    if (playlists.isEmpty) {
      newId = 1; // 如果列表为空，ID 为 1
    } else {
      // 遍历找到当前列表中最大的ID并加 1
      newId = playlists.map((playlist) => playlist.id).reduce((a, b) => a > b ? a : b) + 1;
    }
    // 创建新的播放列表
    PlayListEntity newPlaylist = PlayListEntity(id: newId, name: name, videoIds: []);
    // 添加到播放列表中
    playlists.add(newPlaylist);
    // 保存到本地存储
    await savePlaylists();
    return true; // 添加成功
  }

  // 删除播放列表
  Future<void> deletePlaylist(int id) async {
    if (id == -1) return; // 默认播放列表不允许删除
    playlists.removeWhere((playlist) => playlist.id == id);
    await savePlaylists();
  }

  // 修改播放列表名称
  Future<bool> updatePlaylistName(int id, String newName) async {
    if (id == -1) return false; // 默认播放列表不允许修改名称

    final existingPlaylist = playlists.firstWhereOrNull((playlist) => playlist.name == newName);
    if (existingPlaylist != null) {
      return false; // 名称已存在，修改失败
    }

    final playlist = playlists.firstWhere((playlist) => playlist.id == id);
    playlist.name = newName;
    await savePlaylists();
    return true;
  }

  // 向播放列表中添加视频
  Future<void> addVideosToPlaylist(int id, List<String> videoIds) async {
    final playlist = playlists.firstWhere((playlist) => playlist.id == id);
    playlist.videoIds ??= [];
    playlist.videoIds!.addAll(videoIds);
    await savePlaylists();
  }

  // 从播放列表中移除视频
  Future<void> removeVideosFromPlaylist(int id, List<String> videoIds) async {
    final playlist = playlists.firstWhere((playlist) => playlist.id == id);
    playlist.videoIds?.removeWhere((videoId) => videoIds.contains(videoId));
    await savePlaylists();
  }

  // 清除播放列表中的所有视频
  Future<void> clearVideosFromPlaylist(int id) async {
    final playlist = playlists.firstWhere((playlist) => playlist.id == id);
    playlist.videoIds?.clear();
    await savePlaylists();
  }

  // 自定义排序：支持页面上自由调整顺序
  Future<void> reorderPlaylists(int oldIndex, int newIndex) async {
    if (oldIndex < newIndex) {
      newIndex -= 1;
    }

    final playlist = playlists.removeAt(oldIndex);
    playlists.insert(newIndex, playlist);
    await savePlaylists();
  }

  // 排序播放列表时默认播放列表始终排第一
  Future<void> sortPlaylistsByName({bool ascending = true}) async {
    final nonDefaultPlaylists = playlists.where((p) => p.id != -1).toList();
    nonDefaultPlaylists.sort((a, b) {
      return ascending ? a.name.compareTo(b.name) : b.name.compareTo(a.name);
    });

    playlists.value = [defaultPlaylist, ...nonDefaultPlaylists]; // 默认播放列表始终排第一
    await savePlaylists();
  }
}
